import { server } from "../../utils/config.js";

Page({
  data: {
    server,
    colleges: [],
    teachers: [],
    currentCollegeIndex: 0,
  },

  /**
   * 前往搜索
   */
  toSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },

  /**
   * 前往教师详情
   */
  toTeacherDetails(e) {
    const articleid = e.currentTarget.dataset.articleid
    wx.navigateTo({
      url: '/pages/article/article?aid=' + articleid,
    })
  },

  // 切换学院
  switchCollege: function (e) {
    const index = e.detail.value;
    const collegeId = this.data.colleges[index].id;

    if (index === this.data.currentCollegeIndex) {
      return;
    }

    this.setData({
      currentCollegeIndex: index
    });

    this.getTeacherList(collegeId);
  },

  /**
   * 获取教师列表
   * @param {number} id 学院id
   */
  getTeacherList(id) {
    const that = this;
    wx.fetch({ url: "/teacher/list/" + id })
      .then(res => {
        let resData = res.data;
        that.setData({
          teachers: resData.teachers
        })
      })
  },

  /**
   * 初始化数据
   */
  initData() {
    const that = this;
    wx.fetch({ url: "/teacher/college/list" })
      .then(res => {
        let resData = res.data;
        that.setData({
          colleges: resData.colleges
        });
        if (that.data.colleges.length > 0) {
          that.getTeacherList(that.data.colleges[0].id);
        }
      })
  },

  onLoad(options) {
    this.initData();
  },
});